<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      @open="handleOpen"
      @close="handleClose"
      destroy-on-close
      draggable
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <!-- 基本信息 -->
      <div class="bg-white mt-[10px]">
        <BaseHead>基本信息</BaseHead>
        <div class="p-[10px]">
          <el-form :model="editForm" :rules="rules" label-width="130px" ref="editFormRef">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="评审计划名称" prop="name">
                  <el-input
                    placeholder="评审计划名称"
                    clearable
                    style="width: 40%"
                    v-model="editForm.name"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="评审方案" prop="reviewSchemeId">
                  <CommonSelect
                    :isFetch="false"
                    v-model="editForm.reviewSchemeId"
                    :dataList="psfaList"
                    placeholder="评审方案"
                    style="width: 40%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="评审状态" prop="reviewPlanState">
                  <CommonRadio
                    paramsName="评审计划状态"
                    v-model="editForm.reviewPlanState"
                    valueKey="code"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开始日期" prop="beginDate">
                  <el-date-picker
                    v-model="editForm.beginDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束日期" prop="endDate">
                  <el-date-picker
                    v-model="editForm.endDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24" prop="fileId">
                <el-form-item label="评审指南">
                  <FileUpload
                    class="flex-1"
                    :uploadUrl="uploadUrl"
                    v-model="fileList"
                    :limit="1"
                    tip="附件大小不超过20M"
                    @change="fileChange"
                    exceedLimitType="disabled"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="note">
                  <el-input type="textarea" clearable v-model="editForm.note"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonRadio from "@/views/project/components/CommonRadio.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import { editRecords, recordsDetail } from "@/api/project/xj/xmps";
import { getList } from "@/api/project/xj/psfasz";
import { ElMessage } from "element-plus";
import { assignObj } from "@/utils/main";
import { formatDate } from "@/utils/formatTime";
const fileList = ref([]);
const uploadUrl = `/commonFile/uploadFile?modelName=xjApply`;
const dialogVisible = ref(false);
const operateId = ref(null);
const detailData = ref(null);
const psfaList = ref([]); //评审方案列表
const editFormRef = ref();
const title = computed(() => {
  return operateId.value ? "评审计划编辑" : "转入评审";
});
const editForm = reactive({
  name: "",
  reviewSchemeId: "", //评审方案id
  reviewPlanState: "", //评审状态
  beginDate: "", //开始时间
  endDate: "", //结束时间
  fileId: "", //文件id
  note: "", //备注
  applyInfoId: "", //评审计划id
});
//验证开始日期
const validateBeginDate = (rule, value, callback) => {
  if (value) {
    if (editForm.endDate) {
      if (new Date(value).getTime() >= new Date(editForm.endDate).getTime()) {
        callback(new Error("开始日期应早于结束日期"));
      } else {
        callback();
      }
    } else {
      callback();
    }
  } else {
    callback();
  }
};
//验证结束日期
const validateEndDate = (rule, value, callback) => {
  if (value) {
    if (editForm.beginDate) {
      if (new Date(value).getTime() <= new Date(editForm.beginDate).getTime()) {
        callback(new Error("结束日期应晚于开始日期"));
      } else {
        callback();
      }
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const rules = {
  name: [
    {
      required: true,
      message: "评审计划名称必填",
    },
  ],
  reviewSchemeId: [
    {
      required: true,
      message: "评审方案必填",
    },
  ],
  beginDate: [{ validator: validateBeginDate, trigger: "blur" }],
  endDate: [{ validator: validateEndDate, trigger: "blur" }],
};
const emit = defineEmits(["save-success"]);
//获取详情
const getDetail = async () => {
  const params = {
    planId: operateId.value,
  };
  try {
    const res = await recordsDetail(params);
    detailData.value = res.data;
    //附件列表赋值
    const files = res.data.fileInfo ? res.data.fileInfo : [];
    fileList.value = files.map((item) => {
      return {
        name: item.fileName,
        id: item.id,
      };
    });
  } catch (error) {
    console.log(error);
  }
};
//获取评审方案列表
const getPsfaList = async () => {
  const params = {
    pageNum: 1,
    pageSize: 1000,
  };
  try {
    const res = await getList(params);
    psfaList.value = res.rows;
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = (applyInfoId, applyName) => {
  operateId.value = null;
  editForm.applyInfoId = applyInfoId;
  editForm.name = applyName;
  dialogVisible.value = true;
};
//编辑
const edit = (id) => {
  operateId.value = id;
  dialogVisible.value = true;
  nextTick(async () => {
    await getDetail();
    //表单表格赋值
    assignObj(editForm, detailData.value);
    //日期毫秒数处理成字符串格式
    editForm.beginDate = formatDate(editForm.beginDate, "YYYY-MM-DD");
    editForm.endDate = formatDate(editForm.endDate, "YYYY-MM-DD");
  });
};
//保存
const save = async () => {
  editFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        let params = {
          ...editForm,
          beginDate: editForm.beginDate ? editForm.beginDate : "",
          endDate: editForm.endDate ? editForm.endDate : "",
        };
        if (operateId.value) {
          params.id = operateId.value;
        }
        const res = await editRecords(params);
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          dialogVisible.value = false;
          emit("save-success");
        }
      } catch (error) {
        console.log(error);
      }
    }
  });
};
defineExpose({ add, edit });
//打开弹窗
const handleOpen = () => {
  getPsfaList();
};
//关闭弹窗
const handleClose = () => {
  editFormRef.value.resetFields();
  fileList.value = [];
};
//上传合同附件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.fileId = ids.join(",");
};
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
